import { Component, OnInit, OnDestroy, trigger, transition, state, style, animate } from '@angular/core';
import { ActivatedRoute } from "@angular/router";
import { Subject } from "rxjs/Subject";
import { ReplaySubject } from "rxjs/ReplaySubject";
import { Observable } from "rxjs/Observable";
import { Subscription } from "rxjs/Subscription";
import { CmHttp } from "CmHttp";
import { TOGGLE_STATE } from "utils";
import { BASEURL, STOCKURL } from "shared";
import "rxjs/add/operator/switchMap";

export interface ModalParams {
  isDynamic?: boolean;
  moduleId?: any;
  templateUrl?: string;
  closeObserver: Subject<any>;
  data: any;
}

const CHART_TAB_LIST = [{
  cate: 0,
  text: "模拟交易",
  duration: 1,
  key: 1
  // }, {
  //   cate: 0,
  //   text: "实盘交易",
  //   duration: 2,
  //   key: 2
}];

@Component({
  // moduleId: module.id,
  selector: 'vtrade',
  templateUrl: 'vtrade.component.html',
  styleUrls: ['vtrade.component.less'],
  animations: [
    trigger("expandable", [
      state(TOGGLE_STATE.EXPANDED, style({
        width: "*"
      })),
      state(TOGGLE_STATE.COLLAPSED, style({
        width: "0",
        display: "none"
      })),
      transition(TOGGLE_STATE.COLLAPSED + " <=> " + TOGGLE_STATE.EXPANDED, animate("200ms"))
    ]),
    trigger("vtradeExpand", [
      state(TOGGLE_STATE.EXPANDED, style({
        left: "*"
      })),
      state(TOGGLE_STATE.COLLAPSED, style({
        left: "0"
      })),
      transition(TOGGLE_STATE.COLLAPSED + " <=> " + TOGGLE_STATE.EXPANDED, animate("200ms"))
    ]),
  ]
})
export class VtradeComponent implements OnInit, OnDestroy {
  summarySub = new ReplaySubject(1);
  positionSub = new ReplaySubject(1);
  focusSub = new ReplaySubject(1);
  stockSub = new ReplaySubject(1);  // combo-chart stock source
  stockToggle = new ReplaySubject(1);
  // for summary, terminal and postion
  stockDetailSource = new ReplaySubject(1);
  // for detail-basic and combo-chart
  quoteDetailSource = new ReplaySubject(1);
  paramObs: Observable<any>;
  // 菜单
  listData = CHART_TAB_LIST;
  currentConfig;
  constructor(
    private router: ActivatedRoute,
    private http: CmHttp) { }

  chartLists = ['MA', 'VOL'];
  chartConfig = {
    // mode: 0, // 默认模式0 九宫格模式1
    // theme: 0, // 默认白色颜色主题0
    scrollBar: false, // 是否显示底部滑动条
    // cursorInteract: false, // 是否允许光标交互
    // dragZoom: false, // 是否允许拖拽与缩放
    settingBtn: false, // 是否显示设置按钮
    title: false, // 是否显示股票名称
    menuLeft: true  // 是否在左边显示菜单
  };
  placeSource = Observable.of("vtrade");

  // 自选股分组的初始显示状态
  outlookState = {
    watchlist: TOGGLE_STATE.EXPANDED
  };

  paramForStockSubscription: Subscription;
  paramForChartSubscription: Subscription;
  stockSubscription: Subscription;
  summarySubscription: Subscription;
  positionSubscription: Subscription;
  closeSubscription: Subscription;

  ngOnInit() {
    let { http } = this;

    // 股票代码分发
    this.paramObs = this.router.params
      .filter(params => params["id"])
      .map(params => {
        // console.log('%c vtrade-component symbol:', 'color:#F09', params['id']);
        return { symbol: params["id"].replace("_", ".") };
      });

    // 订阅
    this.paramForStockSubscription = this.paramObs.subscribe(this.stockToggle);
    // for combo-chart
    this.paramForChartSubscription = this.paramObs.subscribe(this.stockSub);

    // 这部分应该放在专门的外壳组件中
    this.stockSubscription = this.stockToggle.filter(quote => quote["symbol"]).switchMap(quote => {
      let reg = /\.XBHS$/g;
      if (reg.test(quote["symbol"])) {
        return Observable.zip(
          http.get(`${STOCKURL}/api/v2/sc/charts/${quote["symbol"]}/summary`),
          (detail) => Object.assign({}, detail.data)
        );
      } else {
        return Observable.zip(
          http.get(`${STOCKURL}/api/v2/sc/stocks/f10/${quote["symbol"]}/headlines`, {}, {cacheAge: http.CACHE_AGE.Instant}),
          http.get(`${STOCKURL}/api/v2/sc/charts/${quote["symbol"]}/summary`),
          (fData, detail) => Object.assign({}, detail.data, fData.data)
        );
      }
    }).subscribe(res => {
      this.stockDetailSource.next(res);
      this.quoteDetailSource.next(res);
    });
    // err => console.log('您可能点击了假数据.暂不支持债券，权证，股转债的交易.')

    // 更新account summary 到 vtrade-buyin component
    this.summarySubscription = this.summarySub.subscribe(data => console.log('terminal summarySub:', data));

    // 加仓，减仓操作
    this.positionSubscription = this.positionSub.subscribe(posData => {
      // { stock{}, isSell }
      // console.debug('position Ctrl Source data:', posData);
      // exchange_type, stock_code
      this.focusSub.next(posData['isSell']);

      let symbol = posData['stock'].stock_code;
      if (posData['stock'].exchange_type === "1") {
        symbol += ".SS";  // 1 for 上证
      } else if (posData['stock'].exchange_type === "2") {
        symbol += ".SZ";  // 2 for 深证
      }
      // console.debug('position Ctrl Source symbol:', symbol);
      this.stockToggle.next({ symbol });
    });

    // close tips modal
    this.closeSubscription = this.closeObserver.subscribe(res => {
      // console.debug('close Observer:', res);
      this.isShowModalTips = false;
    });
  }

  ngOnDestroy() {
    this.paramForStockSubscription ? this.paramForStockSubscription.unsubscribe() : null;
    this.paramForChartSubscription ? this.paramForChartSubscription.unsubscribe() : null;
    this.stockSubscription ? this.stockSubscription.unsubscribe() : null;
    this.summarySubscription ? this.summarySubscription.unsubscribe() : null;
    this.positionSubscription ? this.positionSubscription.unsubscribe() : null;
    this.closeSubscription ? this.closeSubscription.unsubscribe() : null;
  }

  // 更新股票详情，和图表数据
  updateChart(detailData: Object) {
    this.quoteDetailSource.next(detailData);
  }

  // 获取到的account summary数据, 用于计算可买/可卖股票数量
  updateSummary(data: Object) {
    this.summarySub.next(data);
  }

  // 持仓单的加仓，减仓操作
  positionControl(dataObj: Object) {
    this.positionSub.next(dataObj);
  }

  // 提示框
  isShowModalTips = false;
  modalHeading: string;
  modalTips: string[];
  closeObserver = new Subject();
  modalParams = {
    isDynamic: true,
    moduleId: "",
    templateUrl: "",
    closeObserver: this.closeObserver,
    data: "",
  };

  // 显示恒生后台响应的信息到modal
  onModal(msg: string) {
    this.isShowModalTips = true;
    this.modalHeading = "操作提示";
    this.modalTips = [msg];
    // console.debug('show modal tips: ', msg);
  }

  // 开合左侧自选股栏
  toggleState(stateName: string) {
    // console.debug("Toggle State: ", stateName);
    if (!stateName || !this.outlookState || !this.outlookState[stateName]) return;
    this.outlookState[stateName] = this.outlookState[stateName] === TOGGLE_STATE.COLLAPSED ? TOGGLE_STATE.EXPANDED : TOGGLE_STATE.COLLAPSED;
  }
}